package com.shqcjd.yunweiyanoperator.ui.activity;


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.shqcjd.yunweiyanoperator.R;
import com.shqcjd.yunweiyanoperator.api.ApiService;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxObserver;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.yunweiyanoperator.model.ResponseData;
import com.shqcjd.yunweiyanoperator.model.pojo.MajorBean;
import com.shqcjd.yunweiyanoperator.model.pojo.StaffManageBean;
import com.shqcjd.yunweiyanoperator.model.pojo.StaffRequest;
import com.shqcjd.yunweiyanoperator.ui.activity.mine.SpecialtyListActivity;
import com.shqcjd.yunweiyanoperator.ui.adapter.StaffManageAdapter;
import com.shqcjd.yunweiyanoperator.ui.base.BaseActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BasePresenter;
import com.shqcjd.yunweiyanoperator.util.Config;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;
import com.shqcjd.yunweiyanoperator.util.WrapContentLinearLayoutManager;
import com.shqcjd.yunweiyanoperator.widget.AddStaffDialog;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * 员工管理页
 */
public class StaffManageActivity extends BaseActivity {


    List<StaffManageBean.ListBean> mList = new ArrayList<>();
    @BindView(R.id.rv_staff_manage)
    RecyclerView rvStaffManage;
    @BindView(R.id.sr_staff_manage)
    SwipeRefreshLayout srStaffManage;
    @BindView(R.id.rl_isnull)
    RelativeLayout rlIsnull;
    @BindView(R.id.btn_finish)
    ImageView btnFinish;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_include_add)
    TextView tvIncludeAdd;

    private Context mContext;
    private int page = 1;
    private int isRefreshOrLoadMore = 0;//0代表刷新  1代表加载更多
    private StaffManageAdapter staffManageAdapter;
    private AddStaffDialog addStaffDialog;
    private int pageSize;
    private final int PAGE_TOTAL = Config.PAGE_TOTAL;
    private final int ADD_DEPARTMENT = 12114;
    private final int SELECT_SPECIALTY = 12110;
    private int departmentId = -1;
    ArrayList<String> mTypeVals = new ArrayList<>();
    ArrayList<Integer> mTypeId = new ArrayList<>();

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_staff_manage;
    }

    @Override
    public void init() {
        super.init();
        mContext = this;
    }

    @Override
    public void initView() {
        super.initView();
        refreshData();

        tvTitle.setText("员工列表");
        tvIncludeAdd.setVisibility(View.VISIBLE);

        srStaffManage.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });

    }

    private void refreshData() {
        refreshOrLoadMore();
        srStaffManage.setRefreshing(true);
        isRefreshOrLoadMore = 0;
        page = 1;
        mList.clear();
        getDataList(page);
    }

    private void loadMoreData() {
        isRefreshOrLoadMore = 1;
        getDataList(page + 1);
    }

    private void refreshOrLoadMore() {
        if (staffManageAdapter != null) {
            staffManageAdapter.notifyLoadMoreToLoading();
        }
    }


    private void addStaffHttp(String name, String phone, String password, List<Integer> ids) {
//        Map<String, String> map = new HashMap<>();
//        map.put("password", password);
//        map.put("phoneNumber", phone);
//        map.put("userName", name);
//        map.put("departmentId", departmentId+"");
        StaffRequest request = new StaffRequest();
        request.departmentId = departmentId;
        request.userName = name;
        request.phoneNumber = phone;
        request.password = password;
        request.majorIds = ids;
        ApiService.addStaff(new Gson().toJson(request))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData responseData) {
                        if (responseData.retCode == 10000) {
                            refreshData();
                            ToastUtils.showShort(mContext, "添加成功");
                            addStaffDialog.dismiss();
                            addStaffDialog.cleanData();
                            departmentId = -1;
                        } else {
                            ToastUtils.showShort(mContext, responseData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    private void getDataList(int p) {
        Map<String, String> map = new HashMap<>();
        map.put("page", p + "");
        map.put("size", PAGE_TOTAL + "");
        map.put("review", 1+"");//0:未审核,1:已审核,2:审核拒绝  不传就是所有
        ApiService.staffManage(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<StaffManageBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<StaffManageBean> responseData) {
                        if (responseData.retCode != 10000) {
                            return;
                        }
                        mList.addAll(responseData.data.list);
                        pageSize = responseData.data.list.size();
                        if (staffManageAdapter == null) {
                            rvStaffManage.setLayoutManager(new WrapContentLinearLayoutManager(mContext));
                            staffManageAdapter = new StaffManageAdapter(mList, mContext);
                            rvStaffManage.setAdapter(staffManageAdapter);
                            staffManageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                    Intent it = new Intent(mContext, UserInfoActivity.class);
                                    it.putExtra("name", mList.get(position).userName);
                                    it.putExtra("companyName", mList.get(position).businessName);
                                    it.putExtra("phone", mList.get(position).phoneNumber);
                                    it.putExtra("maintainInfo", mList.get(position).info);
                                    it.putExtra("isReview", 0);//员工详情页传0  员工管理页传1
                                    it.putExtra("employeeId", mList.get(position).id);
                                    startActivity(it);
                                }
                            });
                            staffManageAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                                @Override
                                public void onLoadMoreRequested() {
                                    rvStaffManage.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (PAGE_TOTAL > pageSize) {
                                                rvStaffManage.post(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        staffManageAdapter.loadMoreEnd();
                                                    }
                                                });
                                            } else {
                                                loadMoreData();
                                            }
                                        }
                                    });
                                }
                            });
                        }
                        if (isRefreshOrLoadMore == 1) {
                            page = page + 1;
                            staffManageAdapter.loadMoreComplete();
                        }
                        if (mList.size() == 0) {
                            rlIsnull.setVisibility(View.VISIBLE);
                        } else {
                            rlIsnull.setVisibility(View.INVISIBLE);
                        }
                        staffManageAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        srStaffManage.setRefreshing(false);
                    }
                });
    }


    @OnClick({R.id.btn_finish, R.id.tv_include_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_finish:
                finish();
                break;
            case R.id.tv_include_add:
                if(addStaffDialog==null){
                    addStaffDialog = new AddStaffDialog(mContext);
                    addStaffDialog.setOnClickDialogListener(new AddStaffDialog.setOnClickDialogListener() {
                        @Override
                        public void onClickAdd(String name, String phone, String password) {
                            Set<Integer> tagIds = addStaffDialog.getTagIds();
                            List<Integer> ids = new ArrayList<>();
                            for (Integer integer : tagIds) {
                                ids.add(mTypeId.get(integer));
                            }
                            if(departmentId!=-1){
                                addStaffHttp(name, phone, password,ids);
                            }else{
                                ToastUtils.showShort(mContext, "请选择部门");
                            }
                        }

                        @Override
                        public void onAddDepartment() {//部门
                            Intent it = new Intent(mContext, DepartmentSelectActivity.class);
                            startActivityForResult(it, ADD_DEPARTMENT);
                        }

                    });
                }
                if(!addStaffDialog.isShowing()){
                    getMajor();
                    addStaffDialog.show();
                }
                break;
        }
    }

    /**
     * 获取专业tag
     */
    private void getMajor() {
        ApiService.getMajor()
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<MajorBean>>>() {
                    @Override
                    public void _onNext(ResponseData<List<MajorBean>> retData) {
                        if (retData.retCode == 10000) {
                            mTypeVals.clear();
                            mTypeId.clear();
                            for (MajorBean majorBean : retData.data) {
                                mTypeVals.add(majorBean.name);
                                mTypeId.add(majorBean.id);
                            }
                            if (addStaffDialog != null) {
                                addStaffDialog.setTagView(mTypeVals);
                            }
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {

                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==ADD_DEPARTMENT){
            String departmentName = data.getStringExtra("departmentName");
            departmentId = data.getIntExtra("departmentId", -1);
            addStaffDialog.setStr(departmentName);

        }
    }
}
